<?php
/**
 * Created by PhpStorm.
 * User: fengbob
 * Date: 2018/2/14
 * Time: 16:24
 */

namespace app\models;


use app\librarys\Tools;
use app\models\db\Goods;
use app\models\db\GoodsImage;
use app\models\db\File;
use yii\db\Query;

class GoodsExt extends Goods
{
    public static function getGoods($page = 0, $pageSize = 20, $name = '')
    {
        if ($page <= 0) $page = 0;
        $start = $page * $pageSize;

        $query = (new Query())
            ->select(['t1.*,t2.file_id as image_url'])
            ->from('t_goods as t1')
            ->leftJoin('t_goods_image as t2 t2.goods_id=t1.id')
            ->andWhere(['or', 't2.`type`=1', ['or', 'isnull(t2.`type`)']])
            ->andFilterWhere(['like', 'name', $name])
            ->andFilterWhere(['like', 'subtitle', $name])
            ->orderBy('create_datetime desc')
            ->limit($pageSize)
            ->offset($start)
            ->all();

//          $items = db\Goods::find()
//              ->where(['is_enable'=>1])
//              ->leftJoin('t_goods_image as t2 t2.goods_id=t1.id')
//              ->andWhere(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
//              ->andFilterWhere(['like', 'name', $name])
//              ->andFilterWhere(['like', 'subtitle', $name])
//              ->orderBy('create_datetime desc')
//              ->limit($pageSize)
//              ->offset($start)
//              ->all();
        return $query;
    }

    /**
     * 数量
     * @param string $name
     * @return int|string
     */
    public static function getGoodsCount($name = '',$mini_programs_id,$eshop_id='')
    {
        return db\Goods::find()
            ->where(['is_enabled' => 1,'mini_programs_id'=>$mini_programs_id])
            ->andFilterWhere(['like', 'name', $name])
            ->andFilterWhere(['like', 'subtitle', $name])
            ->andFilterWhere(['e_shop_id'=>$eshop_id])
            ->count();
    }


    /**
     * 列表
     * @param int $page
     * @param int $pageSize
     * @param string $name
     * @return mixed
     */
    public static function getGoodsList($page = 0, $pageSize = 20, $name = '',$mini_programs_id,$eshop_id='')
    {
        if ($page <= 0) $page = 0;
        $start = $page * $pageSize;

        $query = (new Query())
            ->select(['t1.*', 't2.file_id as small_image_url'])
            ->from('t_goods as t1')
            ->leftJoin('t_goods_image as t2', 't1.id = t2.goods_id')
            ->where(['is_enabled' => 1,'mini_programs_id'=>$mini_programs_id])
            ->andFilterWhere(['eshop_id'=>$eshop_id])
            ->andWhere(['or', 't2.`type`=1', ['or', 'isnull(t2.`type`)']])
            ->andFilterWhere(['like', 'name', $name])
            ->andFilterWhere(['like', 'subtitle', $name])
            ->orderBy('sort desc')
            ->limit($pageSize)
            ->offset($start)
            ->all();


        if(!empty($query)){
            foreach ($query as &$goods){
                $query_category = (new Query())
                    ->select(['t2.id','t2.name'])
                    ->from(['t_goods_category_goods as t1'])
                    ->leftJoin('t_goods_category as t2','t2.id=t1.goods_category_id')
                    ->where(['t1.goods_id'=>$goods['id']])
                    ->all();
                $goods['categories'] = $query_category;
            }
        }

//        $items = db\Goods::find()
//            ->where(['is_enabled'=>1])
//            ->andFilterWhere(['like', 'name', $name])
//            ->andFilterWhere(['like', 'subtitle', $name])
//            ->orderBy('create_datetime desc')
//            ->limit($pageSize)
//            ->offset($start)
//            ->all();
        return $query;

    }

    /**
     *  根据id获取行
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getGoodsById($id)
    {
        $query = (new Query())
            ->select(['t1.*', 't2.file_id as small_image_url'])
            ->from('t_goods as t1')
            ->leftJoin('t_goods_image as t2', 't1.id = t2.goods_id')
            ->where(['t1.id' => $id])
            ->andWhere(['or', 't2.`type`=1', ['or', 'isnull(t2.`type`)']])
            ->one();
//
//        $item = db\Goods::find()
//            ->where(['id' => $id])
//            ->one();
        return $query;
    }


    /**
     * save data
     * @param $id
     * @param $name
     * @param $display_name
     * @param $subtitle
     * @param $short_name
     * @param $summary
     * @param $unit
     * @param $stock
     * @param $settlement_price
     * @param $selling_price
     * @param $old_price
     * @param $is_enabled
     * @param $is_shelved
     * @param $shelve_datetime
     * @param $is_recommend
     * @param $is_newest
     * @param $is_hot
     * @param $is_free_express
     * @param $is_promotion
     * @param $is_top
     * @param $is_show
     * @param $is_audit
     * @param $audit_datetime
     * @param $audit_remark
     * @param $sell_count
     * @param $collected_count
     * @param $express_money
     * @param $is_invoice
     * @param $is_GGCT
     * @param $is_seven_day
     * @param $is_guarantee
     * @param $is_return_goods
     * @param $mini_programs_id
     * @param $goods_brand_name_id
     * @return bool
     */
    public static function saveGoods($id, $name, $display_name, $subtitle, $short_name, $summary, $unit, $stock, $settlement_price, $selling_price,
                                     $old_price, $is_enabled, $is_shelved, $shelve_datetime, $is_recommend, $is_newest, $is_hot, $is_free_express, $is_promotion,
                                     $is_top, $is_show, $is_audit, $audit_datetime, $audit_remark, $sell_count, $collected_count, $express_money, $is_invoice,
                                     $is_GGCT, $is_seven_day, $is_guarantee, $is_return_goods, $mini_programs_id, $goods_brand_name_id, $sort, $small_img_id, $pro_img_ids, $detail_img_ids)
    {
        $item = Goods::findOne($id);
        if (empty($item)) {
            $item = new db\Goods();
            $item->id = Tools::db_uuid();
            $item->is_enabled = 1;
        }

        $item->name = $name;
        $item->display_name = $display_name;
        $item->subtitle = $subtitle;
        $item->short_name = $short_name;
        $item->summary = $summary;
        $item->unit = $unit;
        $item->stock = $stock;
        $item->is_enabled = $is_enabled;
        $item->settlement_price = $settlement_price;
        $item->selling_price = $selling_price;
        $item->old_price = $old_price;
        $item->is_shelved = $is_shelved;
        $item->shelve_datetime = $shelve_datetime;
        $item->is_recommend = $is_recommend;
        $item->is_newest = $is_newest;
        $item->is_hot = $is_hot;
        $item->is_free_express = $is_free_express;
        $item->is_promotion = $is_promotion;
        $item->is_top = $is_top;
        $item->is_show = $is_show;
        $item->is_audit = $is_audit;
        $item->audit_datetime = $audit_datetime;
        $item->audit_remark = $audit_remark;
        $item->sell_count = $sell_count;
        $item->collected_count = $collected_count;
        $item->express_money = $express_money;
        $item->is_invoice = $is_invoice;
        $item->is_GGCT = $is_GGCT;
        $item->is_seven_day = $is_seven_day;
        $item->is_guarantee = $is_guarantee;
        $item->is_return_goods = $is_return_goods;
        $item->mini_programs_id = $mini_programs_id;
        $item->sort = $sort;

//        $item->goods_brand_name_id = $goods_brand_name_id;

        $result = $item->save();

        $goods_image = GoodsImage::find()
            ->where(['goods_id' => $item->id, 'type' => 1])
            ->one();
        if (empty($goods_image))
            $goods_image = new GoodsImage();

        $goods_image->id = Tools::db_uuid();
        $goods_image->goods_id = $item->id;
        if ($small_img_id) {
            $goods_image->file_id = $small_img_id;
        }
        $goods_image->type = 1;

        $goods_image->save();


        if ($pro_img_ids) {
            foreach ($pro_img_ids as $pro_img_id) {
                $pro_img = new GoodsImage();
                $pro_img->id = Tools::db_uuid();
                $pro_img->goods_id = $item->id;
                $pro_img->file_id = $pro_img_id;
                $pro_img->type = 2;

                $pro_img->save();
            }
        }

        if ($detail_img_ids) {
            foreach ($detail_img_ids as $detail_img_id) {
                $detail_img = new GoodsImage();
                $detail_img->id = Tools::db_uuid();
                $detail_img->goods_id = $item->id;
                $detail_img->file_id = $detail_img_id;
                $detail_img->type = 3;

                $detail_img->save();
            }
        }

        return $result;
    }

    public static function getGoodsImages($id, $type)
    {
        $items = GoodsImage::findAll(['goods_id' => $id, 'type' => $type]);
        return $items;
    }


    public static function deleteGoods($id)
    {
        $images = GoodsImage::findAll(['goods_id' => $id]);

        if (!empty($images)) {
            foreach ($images as $image) {
                $image->delete();
            }
        }

        $item = Goods::findOne($id);
//        $item->is_enable = 0;
//        $result = $item->save();
        $result = $item->delete();

        return $result;
    }

    public static function deleteGoodsImage($id, $img_id)
    {
        $images = GoodsImage::findAll(['goods_id' => $id, 'file_id' => $img_id]);
        if (!empty($images)) {
            foreach ($images as $image) {
                if (!$image->delete()) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取推荐商品的数量
     * @param  int $mini_programs_id [description]
     * @param  int $eshop_id [description]
     * @return int [description]
     * @author milloc
     * @date   2018-04-16
     */
    public static function getRecommendGoodsCount($mini_programs_id, $eshop_id)
    {
        if (empty($mini_programs_id) && empty($eshop_id)) {
            return 0;
        }
        
        $res = Goods::find()->filterWhere(['mini_programs_id' => $mini_programs_id, 'e_shop_id' => $eshop_id])->andWhere(['is_enabled' => 1, 'is_shelved' => 1, 'is_recommend' => 1])->count();
        return $res;
    }

    /**
     * 获取最新商品的数量
     * @param  int $mini_programs_id [description]
     * @param  int $eshop_id [description]
     * @return int [description]
     * @author milloc
     * @date   2018-04-16
     */
    public static function getNewestGoodsCount($mini_programs_id, $eshop_id)
    {
        if (empty($mini_programs_id) && empty($eshop_id)) {
            return 0;
        }

        $res = Goods::find()->filterWhere(['mini_programs_id' => $mini_programs_id, 'e_shop_id' => $eshop_id])->andWhere(['is_enabled' => 1, 'is_shelved' => 1, 'is_newest' => 1])->count();
        return $res;
    }

    /**
     * 获取商店的商品列表
     * id name sell_price is_newest sell_count image
     * @param  integer $eshop_id [description]
     * @param  integer $page [description]
     * @param  integer $page_size [description]
     * @return array [description]
     * @author milloc
     * @date   2018-04-17
     */
    public static function getGoodsListByShop($eshop_id, $page = 0, $page_size = 20)
    {
        $eshop_id = intval($eshop_id);
        $page_size = $page_size > 0 ? $page_size : 0;
        $start = $page > 0 ? $page * $page_size : 0;

        $goods_list = (new Query)->select(['g.id', 'g.name', 'g.selling_price', 'g.is_newest', 'g.sell_count', 'i.file_id image_id'])->from('{{t_goods}} g')->leftJoin('{{t_goods_image}} i', 'i.goods_id = g.id')->where(['g.e_shop_id' => $eshop_id])->andWhere(['or', ['i.type' => 1], 'isnull(`i`.`type`)'])->orderBy('sort desc')->limit($page_size)->offset($start)->all();

        $images_id = array_column($goods_list, 'image_id');
        $image_arr = $images_id ? File::find()->select(['id', 'url'])->where(['id' => $images_id])->asArray()->all() : [];
        $image_arr_rekey = []; // 以 id 为 key
        foreach ($image_arr as $image) {
            if (!isset($image_arr_rekey[$image['id']])) {
                $image_arr_rekey[$image['id']] = $image['url'];
            }
        }
        unset($image_arr);

        $res = [];
        foreach ($goods_list as $goods) {
            $image_url = isset($image_arr_rekey[$goods['image_id']]) ? $image_arr_rekey[$goods['image_id']] : '';
            unset($goods['image_id']);
            $goods['image_url'] = $image_url;
            $res[] = $goods;
        }

        return $res;
    }
}